//index.js

const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    hasUserInfo: false,
    logged: false,
    takeSession: false,
    requestResult: '',
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl'), // 如需尝试获取用户信息可改为false
    banners:[],
    arry:[],
    arry1:[],
    pageNum:1,
    total:0,
    news:[],
    newsIndex:0,
    newstimer:0,
    newItems:'transform: translate(0rpx,0rpx);transition: transform 0.3s;',
    loading:"",
    num:""
  },
  getBanners(){
    return new Promise((resolve,reject)=>{
      wx.get('/index/banners').then((res)=>{
        this.setData({
          banners:res
        })
        resolve()
      })
    })
  },
  //实现上拉刷新请求数据
  onReachBottom(){
    if(this.data.total > this.data.arry1.length){
      this.data.pageNum++
      this.getarry1()
    }
    
  },
  //获取为你推荐数据
  getarry1(){
    return new Promise((resolve,reject)=>{
      this.setData({loading:"数据加载中..."})
      wx.get('/index/recommends',{
        pageNum:this.data.pageNum
      }).then(res=>{
        console.log(res)
        this.setData({
          loading:"已加载完成",
          arry1:this.data.arry1.concat(res.rows),
          total:res.total,
          num:res.rows.length
        })
        resolve()
      })
     
    })
  },
  getarry(){
    return new Promise((resolve,reject)=>{
      wx.get('/index/categorys').then((res)=>{
        this.setData({
          arry:res
        })
        resolve()
      })
    })
  },
  getNews(){
      return new Promise((resolve,reject)=>{
        wx.get('/index/news').then((res)=>{
          this.setData({
            news:res
            })
        this.changeNewsIndex() //触发定时器
        resolve()
      })
      })
     
    
  },
 
  changeNewsIndex(){//新闻轮播
    if( this.data.newstimer){
      clearInterval(this.data.newstimer)
      this.data.newstimer = 0
    }
    this.data.newstimer = setInterval(()=>{
      let newsIndex=this.data.newsIndex
      newsIndex ++
      // if(newsIndex==this.data.news.length) newsIndex = 0///最后一张图切换到第一张
      this.setData({
        newsIndex,
        newItems:'transform: translate(0rpx,-'+newsIndex*42+'rpx);transition: transform 0.3s;'
      })
      if(this.data.newsIndex == this.data.num){
        setTimeout(()=>{
          this.setData({
            newsIndex:0,
            newItems:'transform: translate(0rpx,0rpx);'
          })
        },500)
      }
    },3000)
  },
  onPullDownRefresh(){
    this.data.pageNum = 1
    this.data.arry1=[]
    this.getList()
    console.log("下拉刷新完成")
    wx.stopPullDownRefresh() 
  },
  getList(){
    Promise.all([this.getBanners(),this.getarry(),this.getarry1(), this.getNews(),
    ]).then(()=>{
      console.log("数据加载完成")
    }).catch(e=>{
      console.log("数据加载失败")
    })
  },
  onLoad: function() {
    this.getUserProfile()
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      })
    }
    this.getList()
   
  },
  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '获取你的昵称、头像、地区及性别', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log("1212",res)
        this.setData({
          avatarUrl: res.userInfo.avatarUrl,
          userInfo: res.userInfo,
          hasUserInfo: true,
        })
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo,
        hasUserInfo: true,
      })
    }
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]
        
        // 上传图片
        const cloudPath = `my-image${filePath.match(/\.[^.]+?$/)[0]}`
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath
            
            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      },
      fail: e => {
        console.error(e)
      }
    })
  },

})
